package com.yixing.tech.system.service.impl;

import org.apache.commons.lang3.StringUtils;
import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.enums.ErrCode;
import com.yixing.tech.system.service.IFileService;
import com.yixing.tech.common.utils.QRCodeUtil;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author yixing tech
 * at 2022/5/20
 * describe：
 */
@Service
@Slf4j
public class FileServiceImpl implements IFileService {

    @Resource
    private GridFsTemplate gridFsTemplate;

    @Override
    public String uploadFile(MultipartFile file, String name) throws Exception {
        return gridFsTemplate.store(file.getInputStream(), StringUtils.isEmpty(name) ? file.getOriginalFilename() : name).toString();
    }

    @Override
    public void deleteFile(String id) throws BusinessException {
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is(new ObjectId(id))));
    }

    @Override
    public void downloadFile(HttpServletResponse response, String id) throws Exception {
        GridFSFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(new ObjectId(id))));
        if(file == null)throw new BusinessException(ErrCode.FILE_NOT_EXIST);
        OutputStream outputStream = response.getOutputStream();
        response.setHeader("Access-Control-Expose-Headers", "content-disposition");
        response.setHeader("content-Type", "application/octet-stream");
        // 下载文件的默认名称
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getFilename(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(ErrCode.EXPORT_ERROR);
        }
        IOUtils.copy(gridFsTemplate.getResource(file).getContent(), outputStream);
    }

    @Override
    public void buildQRCode(HttpServletResponse response, String content) throws Exception {
        QRCodeUtil.createCodeToOutputStream(content,response.getOutputStream());

    }
}
